import express from 'express'
import path from 'path'
import session from 'express-session'
import flash from 'express-flash'

import loggerMiddleWare from './middleware/logger'
import errorMiddleWare from './middleware/error'

import MongoStore from "connect-mongo"

import { MONGODB_URI, SESSION_SECRET } from "./utils/secrets"


import * as homeController from "./controllers/home"
import * as apiController from "./controllers/api"
import * as userController from "./controllers/user"

const app = express()

const mongoUrl = MONGODB_URI


// 注册中间件
const registerMiddleWare = () => {
  app.use(express.static(path.join(__dirname, "./public")))
  // app.use(express.static('public'));

  // 解析 JSON 请求体
  app.use(express.json())

  // 解析 URL 编码的请求体
  app.use(express.urlencoded({ extended: true }))

  app.use(session({
    secret: 'keyboard cat',
    resave: true,
    saveUninitialized: true,
    cookie: { secure: true }
  }
    // {
    //   resave: true,
    //   saveUninitialized: true,
    //   secret: SESSION_SECRET as string,
    //   // store: new MongoStore({
    //   //   mongoUrl,
    //   // })
    // }
  ))
  app.use(flash())

  app.use(loggerMiddleWare)
  app.use(errorMiddleWare)
}

registerMiddleWare()

// express configuration
app.set("port", process.env.PORT || 4000)
app.set("views", path.join(__dirname, "../views"))
app.set("view engine", "pug")


// 注册路由
app.get("/", homeController.index)
app.get('/login', userController.getLogin)
app.get('/signup', userController.getSignup)
app.post('/signup', userController.postSignup)

app.get('/api', apiController.getApi)

export default app